nition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    //   左右都为空，或者右为空，不要括号
    //   只有仅左为空，要括号  
    void _tree2str(TreeNode* root,string& str) {

        if(root==nullptr)
            return ;
        
        str+=to_string(root->val);
        if(root->left!=nullptr)
        {
            str+='(';
            _tree2str(root->left,str);
            str+=')';
        }
        else if(root->right!=nullptr)
        {
            str+="()";
        }
        
        if(root->right!=nullptr)
        {
            str+='(';
            _tree2str(root->right,str);
            str+=')';
        }
    }

        string tree2str(TreeNode* root) {
        string str;
        _tree2str(root,str);
        return str;
    }
};
